﻿// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 

using System;
using System.IO;
using svs.Mobile.BeyondMedia.FeedCore;
using svs.Mobile.BeyondMedia.FeedCore.RSS;

namespace svs.Mobile.BeyondMedia.Objects
{
	public static class VersionCheckManager
	{
		#region CheckLoacation enum

		public enum CheckLoacation
		{
			VersionInfoFile,
			VersionInfoTempFile
		}

		#endregion

		private static readonly string _VersionInfoFile = Configuration.VersionInfoPath;
		private static readonly string _VersionInfoTmpFile = Configuration.VersionInfoPath + ".tmp";
		private static DownloadAgent _VersionCheckAgent;
		public static VersionInformation VersionInfo = new VersionInformation();

		static VersionCheckManager()
		{
			VersionInfo = LoadVersionFromInfoFile(CheckLoacation.VersionInfoFile);
		}

		public static double? VersionInfoAgeInHours
		{
			get { return GetFileAgeinHours(_VersionInfoFile); }
		}

		private static VersionInformation LoadVersionFromInfoFile(CheckLoacation location)
		{
			var retVal = new VersionInformation();

			string fileToCheck = location == CheckLoacation.VersionInfoTempFile ? _VersionInfoTmpFile : _VersionInfoFile;

			if (!File.Exists(fileToCheck))
				return retVal;

			StreamReader reader = null;
			try
			{
				reader = File.OpenText(fileToCheck);
				string[] ver = reader.ReadToEnd().Split(new[] {'|'});

				if (ver.Length >= 2)
				{
					retVal.LastPublicVersion = new Version(ver[0]);
					retVal.LastDevVersion = new Version(ver[1]);
				}

				if (ver.Length >= 3)
				{
					retVal.Message = ver[2];
				}
			}
			catch (Exception ex)
			{
				CoreHelper.WriteLogEntry(string.Format("Unable to parse the {0}! Reason: {1}", fileToCheck, ex.Message));
			}
			finally
			{
				if (reader != null)
					reader.Close();
			}

			return retVal;
		}

		public static void CheckForNewVersionIfNeeded()
		{
			bool shouldCheck = true;

			//See if we chancked in the last 24 hours
			double? age = GetFileAgeinHours(_VersionInfoTmpFile);

			if (age.HasValue && age.Value < 24)
			{
				shouldCheck = false;
			}

#if DEBUG
			shouldCheck = true;
#endif

			if (shouldCheck && (_VersionCheckAgent == null || !_VersionCheckAgent.IsDownloading))
			{
				DownloadVersionInfo();
			}
		}

		private static double? GetFileAgeinHours(string file)
		{
			if (File.Exists(file))
			{
				return (DateTime.Now - File.GetLastWriteTime(file)).TotalHours;
			}

			return null;
		}

		private static void DownloadVersionInfo()
		{
			try
			{
				_VersionCheckAgent =
					new DownloadAgent(Configuration.AutoVersionCheckURL, _VersionInfoTmpFile, null);

				_VersionCheckAgent.DownloadCompleted += OnVersionCheckCompleted;
				_VersionCheckAgent.DownloadError += OnVersionCheckFailed;

				_VersionCheckAgent.AllowResume = false;
				CoreHelper.WriteTraceEntry("Checking for New Version");

				_VersionCheckAgent.StartDownload();
			}
			catch (Exception ex)
			{
				OnVersionCheckFailed(string.Empty, ex);
			}
		}

		private static void OnVersionCheckFailed(string destination, Exception ex)
		{
			CoreHelper.WriteLogEntry(string.Format("Unable to check for new version. Reason: {0}", ex.Message));
		}

		private static void OnVersionCheckCompleted(string destination, bool ContentUpdated)
		{
			try
			{
				if (!Equals(VersionInfo, LoadVersionFromInfoFile(CheckLoacation.VersionInfoTempFile)))
				{
					File.Copy(_VersionInfoTmpFile, _VersionInfoFile, true);
					Configuration.NextNotificationTime = DateTime.Now;
				}
			}
			catch (Exception ex)
			{
				CoreHelper.WriteLogEntry(string.Format("Unable to rename the Version Info temp file. Reason: {0}", ex.Message));
			}
		}

		#region Nested type: VersionInformation

		public class VersionInformation
		{
			public Version LastDevVersion;
			public Version LastPublicVersion;
			public string Message;

			public bool IsNewPublicVersionAvailable
			{
				get { return LastPublicVersion != null && LastPublicVersion > Configuration.CurrentProductVersion; }
			}

			public bool IsNewDevVersionAvailable
			{
				get { return LastDevVersion != null && LastDevVersion > Configuration.CurrentProductVersion; }
			}

			public bool HasMessage
			{
				get { return !string.IsNullOrEmpty(Message); }
			}

			public bool Equals(VersionInformation obj)
			{
				if (ReferenceEquals(null, obj)) return false;
				if (ReferenceEquals(this, obj)) return true;
				return Equals(obj.LastPublicVersion, LastPublicVersion) && Equals(obj.LastDevVersion, LastDevVersion) &&
				       Equals(obj.Message, Message);
			}

			public override int GetHashCode()
			{
				unchecked
				{
					int result = (LastPublicVersion != null ? LastPublicVersion.GetHashCode() : 0);
					result = (result*397) ^ (LastDevVersion != null ? LastDevVersion.GetHashCode() : 0);
					result = (result*397) ^ (Message != null ? Message.GetHashCode() : 0);
					return result;
				}
			}
		}

		#endregion
	}
}